import CryptoJS from 'crypto-js'

/**
 * @author IttaHac
 * @createTime 2020年01月10日 15:50
 * @description 加密工具
 */
let keySizes, iterationCounts;
let AesUtil = function (keySize, iterationCount) {
  keySizes = keySize / 32;
  iterationCounts = iterationCount;
};
const that = new AesUtil(128, 147);
AesUtil.prototype.generateKey = function (salt, passPhrase) {
  let key = CryptoJS.PBKDF2(
    passPhrase,
    CryptoJS.enc.Hex.parse(salt), {
      keySize: keySizes,
      iterations: iterationCounts
    });
  return key;
}

/**
 * 加密方法
 * @param {*} salt
 * @param {*} iv
 * @param {*} passPhrase    明文KEY
 * @param {*} plainText     将要加密的字符串
 */
AesUtil.prototype.encrypt = function (salt, iv, passPhrase, plainText) {
  let key = that.generateKey(salt, passPhrase);
  let encrypted = CryptoJS.AES.encrypt(
    plainText,
    key, {
      iv: CryptoJS.enc.Hex.parse(iv)
    });
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

/**
 * 解密方法
 * @param {*} salt
 * @param {*} iv            
 * @param {*} passPhrase    明文KEY
 * @param {*} cipherText    将要解密的字符串
 */
AesUtil.prototype.decrypt = function (salt, iv, passPhrase, cipherText) {
  let key = that.generateKey(salt, passPhrase);
  let cipherParams = CryptoJS.lib.CipherParams.create({
    ciphertext: CryptoJS.enc.Base64.parse(cipherText)
  });
  let decrypted = CryptoJS.AES.decrypt(
    cipherParams,
    key, {
      iv: CryptoJS.enc.Hex.parse(iv)
    });
  return decrypted.toString(CryptoJS.enc.Utf8);
}
export default {
  encrypt: that.encrypt,
  decrypt: that.decrypt,
}